const fs = require('fs');

// 每日统计文件路径
const DAILY_STATS_FILE = process.env.NODE_ENV === 'production' ? '/app/data/daily_stats.json' : './daily_stats.json';

// 读取每日统计数据
function readDailyStats() {
    try {
        if (fs.existsSync(DAILY_STATS_FILE)) {
            const data = fs.readFileSync(DAILY_STATS_FILE, 'utf8');
            return JSON.parse(data);
        }
    } catch (error) {
        console.error('读取每日统计文件失败:', error.message);
    }
    return {};
}

// 获取今天的日期字符串
function getTodayString() {
    const today = new Date();
    return today.toISOString().split('T')[0]; // YYYY-MM-DD格式
}

// 获取指定日期的统计汇总
function getDailyStatsSummary(targetDate = null) {
    const dailyStats = readDailyStats();
    const date = targetDate || getTodayString();
    
    let summary = {
        date: date,
        totalReceived: 0,
        totalCompleted: 0,
        totalFailed: 0,
        deviceCount: 0,
        activeDevices: []
    };
    
    Object.keys(dailyStats).forEach(deviceId => {
        const device = dailyStats[deviceId];
        if (device.history[date]) {
            const dayData = device.history[date];
            summary.totalReceived += dayData.received;
            summary.totalCompleted += dayData.completed;
            summary.totalFailed += dayData.failed;
            summary.deviceCount++;
            
            if (dayData.received > 0 || dayData.completed > 0 || dayData.failed > 0) {
                summary.activeDevices.push({
                    id: deviceId,
                    name: device.deviceName,
                    received: dayData.received,
                    completed: dayData.completed,
                    failed: dayData.failed
                });
            }
        }
    });
    
    return summary;
}

// 获取指定设备的历史统计
function getDeviceHistory(deviceId, days = 7) {
    const dailyStats = readDailyStats();
    if (!dailyStats[deviceId]) {
        return null;
    }
    
    const device = dailyStats[deviceId];
    const today = new Date();
    const history = [];
    
    for (let i = days - 1; i >= 0; i--) {
        const date = new Date(today.getTime() - i * 24 * 60 * 60 * 1000);
        const dateString = date.toISOString().split('T')[0];
        
        if (device.history[dateString]) {
            history.push({
                date: dateString,
                ...device.history[dateString]
            });
        } else {
            history.push({
                date: dateString,
                received: 0,
                completed: 0,
                failed: 0
            });
        }
    }
    
    return {
        deviceId: deviceId,
        deviceName: device.deviceName,
        history: history
    };
}

// 显示帮助信息
function showHelp() {
    console.log(`
📊 Cysic任务统计查看工具

用法:
  node viewStats.js [命令] [参数]

命令:
  today              查看今日统计汇总
  date <YYYY-MM-DD>  查看指定日期的统计汇总
  device <设备ID>    查看指定设备的7天历史统计
  device <设备ID> <天数>  查看指定设备的N天历史统计
  list               列出所有设备
  help               显示此帮助信息

示例:
  node viewStats.js today
  node viewStats.js date 2024-01-15
  node viewStats.js device 12345
  node viewStats.js device 12345 14
  node viewStats.js list
`);
}

// 显示今日统计
function showTodayStats() {
    const summary = getDailyStatsSummary();
    
    console.log('📊 今日任务统计汇总');
    console.log('='.repeat(50));
    console.log(`日期: ${summary.date}`);
    console.log(`今日接收任务总数: ${summary.totalReceived}`);
    console.log(`今日完成任务总数: ${summary.totalCompleted}`);
    console.log(`今日失败任务总数: ${summary.totalFailed}`);
    console.log(`今日活跃设备数: ${summary.activeDevices.length}`);
    
    if (summary.activeDevices.length > 0) {
        console.log('\n📋 今日活跃设备详情:');
        summary.activeDevices.forEach((device, index) => {
            console.log(`${index + 1}. ${device.name} (ID: ${device.id})`);
            console.log(`   接收: ${device.received} | 完成: ${device.completed} | 失败: ${device.failed}`);
        });
    } else {
        console.log('\n💤 今日暂无活跃设备');
    }
}

// 显示指定日期统计
function showDateStats(targetDate) {
    const summary = getDailyStatsSummary(targetDate);
    
    console.log(`📊 ${targetDate} 任务统计汇总`);
    console.log('='.repeat(50));
    console.log(`日期: ${summary.date}`);
    console.log(`接收任务总数: ${summary.totalReceived}`);
    console.log(`完成任务总数: ${summary.totalCompleted}`);
    console.log(`失败任务总数: ${summary.totalFailed}`);
    console.log(`活跃设备数: ${summary.activeDevices.length}`);
    
    if (summary.activeDevices.length > 0) {
        console.log('\n📋 活跃设备详情:');
        summary.activeDevices.forEach((device, index) => {
            console.log(`${index + 1}. ${device.name} (ID: ${device.id})`);
            console.log(`   接收: ${device.received} | 完成: ${device.completed} | 失败: ${device.failed}`);
        });
    } else {
        console.log('\n💤 该日期暂无活跃设备');
    }
}

// 显示设备历史统计
function showDeviceHistory(deviceId, days = 7) {
    const history = getDeviceHistory(deviceId, days);
    
    if (!history) {
        console.log(`❌ 未找到设备 ${deviceId} 的统计数据`);
        return;
    }
    
    console.log(`📊 设备 ${history.deviceName} (ID: ${deviceId}) 最近${days}天统计`);
    console.log('='.repeat(50));
    
    let totalReceived = 0, totalCompleted = 0, totalFailed = 0;
    
    history.history.forEach(day => {
        totalReceived += day.received;
        totalCompleted += day.completed;
        totalFailed += day.failed;
        
        if (day.received > 0 || day.completed > 0 || day.failed > 0) {
            console.log(`${day.date}: 接收${day.received} | 完成${day.completed} | 失败${day.failed}`);
        } else {
            console.log(`${day.date}: 无活动`);
        }
    });
    
    console.log('\n📈 汇总统计:');
    console.log(`总接收: ${totalReceived} | 总完成: ${totalCompleted} | 总失败: ${totalFailed}`);
    console.log(`完成率: ${totalReceived > 0 ? ((totalCompleted / totalReceived) * 100).toFixed(2) : 0}%`);
}

// 列出所有设备
function listAllDevices() {
    const dailyStats = readDailyStats();
    const devices = Object.keys(dailyStats);
    
    if (devices.length === 0) {
        console.log('📭 暂无设备统计数据');
        return;
    }
    
    console.log('📋 所有设备列表');
    console.log('='.repeat(50));
    
    devices.forEach((deviceId, index) => {
        const device = dailyStats[deviceId];
        const dates = Object.keys(device.history);
        const latestDate = dates.sort().pop();
        
        console.log(`${index + 1}. ${device.deviceName} (ID: ${deviceId})`);
        console.log(`   最后活动: ${latestDate || '无记录'}`);
        console.log(`   历史记录天数: ${dates.length}`);
    });
}

// 主函数
function main() {
    const args = process.argv.slice(2);
    
    if (args.length === 0) {
        showTodayStats();
        return;
    }
    
    const command = args[0].toLowerCase();
    
    switch (command) {
        case 'today':
            showTodayStats();
            break;
            
        case 'date':
            if (args[1]) {
                showDateStats(args[1]);
            } else {
                console.log('❌ 请指定日期，格式: YYYY-MM-DD');
            }
            break;
            
        case 'device':
            if (args[1]) {
                const days = args[2] ? parseInt(args[2]) : 7;
                showDeviceHistory(args[1], days);
            } else {
                console.log('❌ 请指定设备ID');
            }
            break;
            
        case 'list':
            listAllDevices();
            break;
            
        case 'help':
        case '--help':
        case '-h':
            showHelp();
            break;
            
        default:
            console.log(`❌ 未知命令: ${command}`);
            showHelp();
    }
}

// 运行脚本
main(); 